const domSymbol = Symbol('watermark-dom');

type TypeParams = {
  title: string,
  titleColor?: string,
  subtitle?: string,
  subtitleColor?: string,
  width?: number,
  height?: number
}

export function useWatermark(appendEl: HTMLElement | null = document.body) {
  let func: Func = () => {
    // console.log('水印resize');
  };
  const id = domSymbol.toString();
  const clear = () => {
    const domId = document.getElementById(id);
    if (domId) {
      appendEl?.removeChild(domId);
    }
    window.removeEventListener('resize', func);
  };

  const createWatermark = (params: TypeParams) => {
    clear();

    const can = document.createElement('canvas');
    can.width = params.width || 200;
    can.height = params.height || 120;

    const cans = can.getContext('2d');
    if (cans) {
      cans.rotate((-20 * Math.PI) / 120);
      cans.font = '15px Vedana';
      cans.fillStyle = params.titleColor || '#dcdfe6';
      cans.textAlign = 'left';
      cans.textBaseline = 'middle';
      cans.fillText(params.title, can.width / 20, can.height);

      cans.fillStyle = params.subtitleColor || '#eaedf6';
      cans.fillText(params.subtitle || '', can.width / 20, can.height + 20);
    }

    const div = document.createElement('div');
    div.id = id;
    div.style.pointerEvents = 'none';
    div.style.top = '0px';
    div.style.left = '0px';
    div.style.position = 'absolute';
    div.style.zIndex = '100000000';
    div.style.width = `${document.documentElement.clientWidth}px`;
    div.style.height = `${document.documentElement.clientHeight}px`;
    div.style.background = `url(${can.toDataURL('image/png')}) left top repeat`;
    appendEl?.appendChild(div);
    return id;
  };

  function setWatermark(params: TypeParams) {
    createWatermark(params);
    func = () => {
      createWatermark(params);
    };
    window.addEventListener('resize', func);
  }

  return { setWatermark, clear };
}
